package com.qf.cloud2203.couponRecord.consumer;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.cloud2203.couponRecord.coupons.mapper.CouponMapper;
import com.qf.cloud2203.couponRecord.coupons.mapper.Users_CouponMapper;
import com.qf.cloud2203.couponRecord.coupons.service.impl.UsersServiceImpl;
import com.qf.cloud2203.couponRecord.repository.CouponRepository;
import com.qf.cloud2203.domain.entity.Coupon;
import com.qf.cloud2203.domain.entity.Users;
import com.qf.cloud2203.domain.entity.UserCoupon;
import com.qf.cloud2203.getcoupons.coupons.service.impl.CouponServiceImpl;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Component
public class CouponConsumer {
    @Autowired
    CouponRepository couponRepository;
    @Autowired
    UsersServiceImpl usersServiceImpl;
    @Autowired
    Users_CouponMapper users_couponMapper;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    CouponMapper couponMapper;
    /**
     * mq消费者接收消息并记录流水，存入sql数据库
     *
     * @param usersJson
     * @param channel
     * @param message
     * @throws IOException
     */
    //@Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = "coupons")
    public void getMsg(String usersJson, Channel channel, Message message) throws IOException {
        Users users = JSONUtil.toBean(usersJson, Users.class);
        usersServiceImpl.save(users);
        Users usersDB = usersServiceImpl.getOne(new QueryWrapper<Users>().eq("phone", users.getPhone()));
        users.setId(usersDB.getId());
        couponRepository.save(users);
        UserCoupon users_coupon = new UserCoupon();
        users_coupon.setUserId(usersDB.getId());
        users_coupon.setCouponId(users.getCouponId());
        users_couponMapper.insert(users_coupon);
        //Coupon couponDB = couponMapper.selectOne(new QueryWrapper<Coupon>().eq("couponId",users.getCouponId()));
        couponMapper.update(null,new UpdateWrapper<Coupon>().eq("couponId",users.getCouponId()).set("state",0));
        //手工ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }
}
